package com.such.kit.database.dialect;

import java.util.HashSet;
import java.util.Set;
import com.such.kit.database.exception.DatabaseException;
import com.such.kit.resource.support.ReadResource;
import com.such.kit.string.StringCommons;
import com.such.kit.validate.ValidateCommons;

/**
 * @作者 SUCH
 * @日期 2017-9-1 下午4:41:58
 * @描述 数据库保留字工厂
 * <p>
 * 格式：reserved_words=word1 | word2 ...
 * </p>
 */
public class ReservedWordFactory {

	/** reservedSymbols：数据库保留符号集合 */
	private static Set<String> reservedSymbols = new HashSet<String>();
	static {
		// 初始化特殊符号
		reservedSymbols.add("!");
		reservedSymbols.add("!=");
		reservedSymbols.add("&");
		reservedSymbols.add("(");
		reservedSymbols.add(")");
		reservedSymbols.add("*");
		reservedSymbols.add("+");
		reservedSymbols.add(",");
		reservedSymbols.add("-");
		reservedSymbols.add(".");
		reservedSymbols.add("/");
		reservedSymbols.add(":");
		reservedSymbols.add(";");
		reservedSymbols.add("<");
		reservedSymbols.add("<<");
		reservedSymbols.add("<=");
		reservedSymbols.add("=");
		reservedSymbols.add("=>");
		reservedSymbols.add(">");
		reservedSymbols.add(">=");
		reservedSymbols.add("@");
		reservedSymbols.add("[");
		reservedSymbols.add("]");
		reservedSymbols.add("^");
		reservedSymbols.add("{");
		reservedSymbols.add("|");
		reservedSymbols.add("}");
	}

	/** reservedWords：数据库保留字集合 */
	private Set<String> reservedWords = new HashSet<String>();
	private String resourceName;

	public ReservedWordFactory(String resourceName) {
		this.resourceName = resourceName;
		init();
	}

	private void init() {
		// 初始化关键字
		String words = ReadResource.getValue(this.resourceName, "reserved_words");
		if (ValidateCommons.isEmpty(words)) {
			throw new DatabaseException(StringCommons.merger("未在 [", this.resourceName, "] 中找到 [reserved_words] 对应的函数模板"));
		}
		for (String word : words.split("\\|")) {
			this.reservedWords.add(StringCommons.toUpperCase(word.trim()));
		}
	}

	/**
	 * <p>方法名：isReserved</p>
	 * <p>描述：检查是否为保留字或保留符号</p>
	 * @param value 值
	 * @return 是否为保留字
	 */
	public boolean isReserved(String value) {
		return isReservedWord(value) || isReservedSymbol(value);
	}

	/**
	 * <p>方法名：isReservedWord</p>
	 * <p>描述：检查是否为保留字</p>
	 * @param word 字
	 * @return 是否为保留字
	 */
	public boolean isReservedWord(String word) {
		return this.reservedWords.contains(StringCommons.toUpperCase(word.trim()));
	}

	/**
	 * <p>方法名：isReservedSymbol</p>
	 * <p>描述：检查是否为保留符号</p>
	 * @param symbol 符号
	 * @return 是否为保留符号
	 */
	public static boolean isReservedSymbol(String symbol) {
		return reservedSymbols.contains(symbol.trim());
	}

}
